cmake_minimum_required(VERSION 3.10)

# 项目名称
project(Template)

file(GLOB SRCS
    ${PROJECT_SOURCE_DIR}/app/*.cpp
    ${PROJECT_SOURCE_DIR}/system/*.cpp
    ${PROJECT_SOURCE_DIR}/system/camellia/utils/Port/*.cpp
    ${PROJECT_SOURCE_DIR}/system/camellia/utils/Pin/*.cpp
    ${PROJECT_SOURCE_DIR}/system/drivers/gpio/*.cpp
)

include_directories(
    ${PROJECT_SOURCE_DIR}/app
    ${PROJECT_SOURCE_DIR}/system
)

include_directories(
    ${PROJECT_SOURCE_DIR}/system/camellia/utils/Port
    ${PROJECT_SOURCE_DIR}/system/camellia/utils/Pin
    ${PROJECT_SOURCE_DIR}/system/drivers/gpio/
)

set(STARTUP_FILE ${PROJECT_SOURCE_DIR}/startup.s)

set(LINKER_SCRIPT ${CMAKE_CURRENT_SOURCE_DIR}/link.ld)

set(LIBS_FLAG "-lc -lstdc++ -lnosys -lm")

enable_language(ASM)
# 设置交叉编译工具链
set(CMAKE_C_COMPILER riscv-none-elf-gcc)
set(CMAKE_CXX_COMPILER riscv-none-elf-g++)
set(CMAKE_ASM_COMPILER riscv-none-elf-gcc)
set(CMAKE_OBJCOPY riscv-none-elf-objcopy)
set(CMAKE_SIZE riscv-none-elf-size)

set(MCU_FLAGS "-march=rv32imac -mabi=ilp32")
set(CMAKE_ASM_FLAGS "-x assembler-with-cpp ${MCU_FLAGS} -g -msmall-data-limit=8 -msave-restore -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fno-common -Wunused -Wuninitialized -std=gnu99")
set(CMAKE_C_FLAGS "${MCU_FLAGS} -g -msmall-data-limit=8 -msave-restore -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fno-common -Wunused -Wuninitialized -std=gnu99")
set(CMAKE_CXX_FLAGS "${MCU_FLAGS} -g -msmall-data-limit=8 -msave-restore -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fno-common -Wunused -Wuninitialized")

set(CMAKE_EXE_LINKER_FLAGS "${MCU_FLAGS}  -msmall-data-limit=8 -msave-restore -O0 -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fno-common -Wunused -Wl,-u_printf_float -Wuninitialized -g -T ${LINKER_SCRIPT} -nostartfiles -Xlinker --gc-sections -Wl,-Map=${PROJECT_BINARY_DIR}/${PROJECT_NAME}.map --specs=nano.specs --specs=nosys.specs ${LIBS_FLAG}")

add_executable(${PROJECT_NAME}.elf ${STARTUP_FILE} ${SRCS})

add_custom_command(TARGET "${PROJECT_NAME}.elf" POST_BUILD
COMMAND ${CMAKE_OBJCOPY} -Obinary ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.elf ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.bin
COMMAND ${CMAKE_OBJCOPY} -Oihex ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.elf ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.hex
COMMENT "Building binary file and hex file"
COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.bin "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.bin"
COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.hex "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.hex"
COMMAND ${CMAKE_SIZE} --format=berkeley ${PROJECT_NAME}.elf ${PROJECT_NAME}.hex
COMMENT "Invoking: Cross RISC-V GNU Print Size"
)
